package com.sec.etech.org.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sec.etech.org.dao.ETechGroupViewMapper;
import com.sec.etech.org.dao.ProjDesigndprt2Mapper;
import com.sec.etech.org.model.EtechOrgTree;
import com.sec.etech.org.model.GroupView;
import com.sec.etech.org.model.ProjDesigndprt2;
import com.sec.etech.sys.util.ContextUtil;
import com.sec.etech.sys.util.DbUtil;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.openbpm.org.api.model.IGroup;
import org.openbpm.org.core.dao.OrgRelationDao;
import org.openbpm.org.core.manager.GroupManager;
import org.openbpm.org.core.model.Group;
import org.openbpm.org.core.model.OrgRelation;
import org.openbpm.org.service.impl.DefaultGroupService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Primary;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Collections.EMPTY_LIST;

@Primary
@Service("etechGroupService")
public class EtechGroupService extends DefaultGroupService {

    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    GroupManager groupManager;

    @Resource
    EtechRelationService etechRelationService;

    @Resource
    OrgRelationDao orgRelationDao;

    @Resource
    ETechGroupViewMapper groupViewMapper;

    @Resource
    ProjDesigndprt2Mapper projDesigndprt2Mapper;



    /**
     * 获取本级和父级部门的TWSAP日报收件人
     * @param dprtId
     * @return
     */
    public List<String> getTwsapDailyManager2(String dprtId) {
        Set<String> ss = new HashSet<>();
        List<ProjDesigndprt2> projDesigndprts = projDesigndprt2Mapper.selectList(new QueryWrapper<ProjDesigndprt2>().lambda()
                .eq(ProjDesigndprt2::getDprtid, Long.parseLong(dprtId))
        );
        if (!projDesigndprts.isEmpty()){

            ProjDesigndprt2 designdprt2 = projDesigndprts.get(0);
            String manager = designdprt2.getTwsapDailyManager();
            if (StringUtils.isNotBlank(manager)){
                String[] managers = manager.split(",");
                ss.addAll((Arrays.asList(managers)));
            }
        }

        return new ArrayList<>(ss);
    }

    /**
     * 获取本级和父级部门的TWSAP日报收件人
     * @param dprtId
     * @return
     */
    public List<String> getTwsapDailyManager(String dprtId) {
        Set<String> ss = new HashSet<>();
        List<ProjDesigndprt2> projDesigndprts = projDesigndprt2Mapper.selectList(new QueryWrapper<ProjDesigndprt2>().lambda()
                .eq(ProjDesigndprt2::getDprtid, Long.parseLong(dprtId))
        );
        if (!projDesigndprts.isEmpty()){

            ProjDesigndprt2 designdprt2 = projDesigndprts.get(0);
            String manager = designdprt2.getTwsapDailyManager();
            if (StringUtils.isNotBlank(manager)){
                String[] managers = manager.split(",");
                ss.addAll((Arrays.asList(managers)));
            }
        }

        String pdprtid = getParentDprtId(dprtId);
        List<ProjDesigndprt2> projDesigndprts2 = projDesigndprt2Mapper.selectList(new QueryWrapper<ProjDesigndprt2>().lambda()
                .eq(ProjDesigndprt2::getDprtid, Long.parseLong(pdprtid))
        );
        if (!projDesigndprts2.isEmpty()){

            ProjDesigndprt2 designdprt2 = projDesigndprts2.get(0);
            String manager = designdprt2.getTwsapDailyManager();
            if (StringUtils.isNotBlank(manager)){
                String[] managers = manager.split(",");
                ss.addAll((Arrays.asList(managers)));
            }
        }

        return new ArrayList<>(ss);
    }

    /**
     * 获取某部门的厂级、部级、处级、科级部门id。输入(设计一室id，4)，返回一室所在的部，即新厂技术部
     *
     * @param dprtid 组织id
     * @param level  其父部门的等级。2-厂级，4-部级，5-处级，6-科级
     * @return String 特定等级的父组织id,错误时返回“”
     * @author PengMaochang
     * @date 2021/12/7 11:13
     */
    public String getParentDprtByLevel(String dprtid, Integer level) {
        String parentDprtId = "";
        String sql = "select level_id{} from org_group_fullname where group_id = '{}'";
        try {
            parentDprtId = jdbcTemplate.queryForObject(StrUtil.format(sql, level, dprtid), String.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return parentDprtId;
    }

    /**
     * 获取当前用户所在设计科室
     *
     * @return
     */
    public String getCurUserDesigndprtid() {
        return getDesigndprtidByUserId(Long.parseLong(ContextUtil.getCurrentUserId()));
    }

    /**
     * 根据用户id获取用户所在设计科室
     *
     * @param userid
     * @return
     */
    public String getDesigndprtidByUserId(Long userid) {
        if (userid != null) {
            String sql = "select a.designdprtid from proj_plantask_z_designdprt a left join org_users b on a.dprtid = b.dprtid where b.id_ = " + userid;
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if (CollUtil.isNotEmpty(list)) {
                return MapUtil.getStr(list.get(0), "designdprtid");
            }
        }
        return null;
    }

    /**
     * 根据设计科室序号获取部门班组
     *
     * @param designdprtid
     * @return
     */
    public Long getDprtidByDesigndprtid(Long designdprtid) {
        if (designdprtid != null) {
            String sql = "select dprtid from proj_plantask_z_designdprt  where designdprtid = " + designdprtid;
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if (CollUtil.isNotEmpty(list)) {
                return MapUtil.getLong(list.get(0), "dprtid");
            }
        }
        return null;
    }

    public String getDprtNameByDesigndprtid(String designdprtid) {
        if (designdprtid != null) {
            String sql = "select designdprtname from proj_plantask_z_designdprt  where designdprtid = " + designdprtid;
            return jdbcTemplate.queryForObject(sql, String.class);
        }
        return "";
    }

    public String getDprtNameByDesigndprtids(List<String> groupIds){
        if (groupIds != null){
            return groupIds.stream().map(this::getDprtNameByDesigndprtid).collect(Collectors.joining(","));
        }else{
            return "";
        }
    }

    /**
     * 获得部门班组的设计科室序号
     *
     * @param dprtid
     * @return
     */
    public Long getDesigndprtidByDprtid(Long dprtid) {
        if (dprtid != null) {
            String sql = "select designdprtid from proj_plantask_z_designdprt  where dprtid = " + dprtid;
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if (CollUtil.isNotEmpty(list)) {
                return MapUtil.getLong(list.get(0), "designdprtid");
            }
        }
        return null;
    }


    /**
     * 根据部门科室获取计划负责人
     * @param dprtId
     * @return
     */
    public List<Long> getDesigndprtPlannersByDprtId(String dprtId){
        String sql = "select dp.uid from proj_plantask_z_designdprt d,proj_plantask_z_designdprt_planners dp " +
                " where dp.uid is not null and d.designdprtid=dp.designdprtid and dp.active=1 and d.active=1 and d.dprtid=" + dprtId;
        return jdbcTemplate.queryForList(sql, Long.TYPE);
    }
    /**
     * 根据用户id获取权限
     * @param userId
     * @return
     */
    public Set<String> getUserRightByUserId(String userId) {
        List<? extends IGroup> list = this.getGroupsByUserId(userId);
        Set<String> rights = new HashSet();
        rights.add(String.format("%s-%s", userId, "user"));
        if (CollectionUtil.isEmpty(list)) {
            return rights;
        } else {
            Iterator var4 = list.iterator();
            while(var4.hasNext()) {
                IGroup group = (IGroup)var4.next();
                rights.add(String.format("%s-%s", group.getGroupId(), group.getGroupType()));
            }
            return rights;
        }
    }

    /**
     * 参数：columnName-主表主键名称，mTableName-主表名称，sTableName-子表名称，groupId-用户直接所属部门班组
     * @param params
     * @return
     */
    public Long getContrastPKByParams(Map<String,String> params){
        Map<String,Object> map = this.getGroupIdByType(params.get("groupId"));
        List<String> dprtIdList = new ArrayList<>();//获取用户所有上级部门
        dprtIdList.add(params.get("groupId"));
        for(int i=0; i<10; i++) {
            if(map!=null) {
                dprtIdList.add(map.get("parent_id_").toString());
            }
            if (map.get("parent_id_") != null && !"0".equals(map.get("parent_id_").toString())) {
                map = this.getGroupIdByType(map.get("parent_id_").toString());
            }else {
                break;
            }
        }
        //select ds.dprtsid,ds.dprtid from rands_task_z_dprts d,rands_task_z_dprts_sub ds
        //where d.dprtsid=ds.dprtsid and ds.active=1 and ds.dprtid in(6,10);
        String sql = "select ds." +params.get("columnName")+ ",ds.dprtid from " +params.get("mTableName")+ " d," +params.get("sTableName")+
                " ds where d." +params.get("columnName")+ "=ds." +params.get("columnName")+ " and ds.active=1 and ds.dprtid in(" +String.join(",",dprtIdList)+ ")";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list!=null && list.size()>0){
            return (Long) list.get(0).get(params.get("columnName"));
        }
        return null;
    }

    //查询部门科室表
    private Map<String,Object> getGroupIdByType(String groupid){
        Map<String,Object> map = null;
        String sql = "select g.id_,g.parent_id_,g.type_ from org_group g where g.id_=? ";
        List<Map<String, Object>> gList = jdbcTemplate.queryForList(sql, groupid);
        if(gList!=null && gList.size()>0){
            map = gList.get(0);
        }
        return map;
    }
    /**
     * 获取所有部门ID（包含本身以及所有子部门，包含多层子部门）
     * @param dprtId
     * @return
     */
    public List<String> getAllDprtIdsByDprtId(String dprtId){
        List<String> dprtIds = new ArrayList<>();
        List<String> param = new ArrayList<>();
        param.add(dprtId);
        dprtIds.addAll(param);
        for(int i=0; i<10; i++){//防止死循环
            List<String> list = this.getSubDprtIds(param);
            if(CollectionUtil.isEmpty(list)){
                break;
            }
            param = list;
            dprtIds.addAll(param);
        }
        return dprtIds;
    }
    /**
     * 获取子部门
     * @param dprtIds
     * @return
     */
    private List<String> getSubDprtIds(List<String> dprtIds){
        List<String> res = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(dprtIds)){
           for(String id: dprtIds){
               List<String> list = getSubDprtIds(id);
               res.addAll(list);
           }
        }
        return res;
    }
    /**
     * 获取当前部门的子部门（只包含一层）
     * @param dprtId
     * @return
     */
    @Cacheable("subDprtId")
    public List<String> getSubDprtIds(String dprtId){
        String sql = "select id_ from org_group where parent_id_ = ? ";
        return  jdbcTemplate.query(sql, new Object[]{dprtId}, new RowMapper<String>(){
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("id_");
            }
        });
    }

    public String getParentDprtId(String dprtId){
        String sql = "select parent_id_ from org_group where id_ = ? ";
        return jdbcTemplate.queryForObject(sql, new Object[]{dprtId}, new RowMapper<String>() {
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("parent_id_");
            }
        });
    }

    /**
     * 获取部门主管UID
     * （数据wss_dprt_manager）
     * @param dprtId
     * @return
     */
    public List<String> getDprtManager(String dprtId){
        return getDprtPost(dprtId, "1");
    }

    /**
     * 获取部门助理UID
     * （数据wss_dprt_assistant）
     * @param dprtId
     * @return
     */
    public List<String> getDprtAssistant(String dprtId){
        return getDprtPost(dprtId, "2");
    }

    /**
     * 获取部门内勤UID
     * （数据wss_dprt_inter）
     * @param dprtId
     * @return
     */
    public List<String> getDeprtInter(String dprtId){
        return getDprtPost(dprtId, "3");
    }

    /**
     * 2022-05-18 修改为设计科室配置
     * wss部门基础方法
     *
     * @param dprtId
     * @param type 1-manager, 2-assistant, 3-inter
     * @return
     */
    private List<String> getDprtPost(String dprtId, String type){
        List<String> uids = new ArrayList<>();
        List<ProjDesigndprt2> projDesigndprts = projDesigndprt2Mapper.selectList(new QueryWrapper<ProjDesigndprt2>().lambda()
                .eq(ProjDesigndprt2::getDprtid, Long.parseLong(dprtId))
        );

        if (projDesigndprts == null || projDesigndprts.isEmpty()){
            return uids;
        }

        String manager = projDesigndprts.get(0).getDprtManager();
        if("2".equals(type)){
            manager = projDesigndprts.get(0).getDprtAssistant();
        }else if("3".equals(type)){
            manager = projDesigndprts.get(0).getDprtInner();
        }
        if (StringUtils.isNotBlank(manager)){
            String[] ss = manager.split(",");
            uids.addAll(Arrays.asList(ss));
        }

//        String table = "wss_dprt_manager";
//        if("2".equals(type)){
//            table = "wss_dprt_assistant";
//        }else if("3".equals(type)){
//            table = "wss_dprt_inter";
//        }
//        String sql = "select uid from {} where dprtid=? and active=1 and uid in (select CAST(id_ as SIGNED) from org_user where status_ = 1) order by orderby";
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(StrUtil.format(sql, table), dprtId);
//        if(CollectionUtil.isNotEmpty(list)){
//            for(Map<String,Object> row: list){
//                uids.add(MapUtil.getStr(row, "uid"));
//            }
//        }
        return uids;
    }



    // 主管的含义，现在是todo manager!
    // 2022-05-18 通过人找到设计科室
    @Cacheable("twsapMasterGroupIds")
    public String[] getTwsapMasterGroupIds(String userId) {
        Set<String> setGroupIds = new HashSet<>();
        //wss_dprt_manager
        //wss_dprt_assistant
        //wss_dprt_inter 增加内勤 2020/11/23

        List<ProjDesigndprt2> designdprt2 = projDesigndprt2Mapper.selectList(new QueryWrapper<ProjDesigndprt2>().lambda().gt(ProjDesigndprt2::getDesigndprtid, 0));
        for (ProjDesigndprt2 dprt : designdprt2){
            Set<String> uids = new HashSet<>();
//            if (StringUtils.isNotBlank(dprt.getDprtManager())){
//                String[] ss = dprt.getDprtManager().split(",");
//                uids.addAll(Arrays.asList(ss));
//            }
//            if (StringUtils.isNotBlank(dprt.getDprtAssistant())){
//                String[] ss = dprt.getDprtAssistant().split(",");
//                uids.addAll(Arrays.asList(ss));
//            }
            if (StringUtils.isNotBlank(dprt.getTwsapStatManager())){
                String[] ss = dprt.getTwsapStatManager().split(",");
                uids.addAll(Arrays.asList(ss));
            }
            if (uids.contains(userId)){
                setGroupIds.add(dprt.getDprtid().toString());
            }

        }

//        if(listDprt!=null){
//            for(Map<String, Object> row: listDprt){
//                String dprtId = MapUtil.getStr(row, "dprtid");
//                setGroupIds.add(dprtId);
//            }
//        }
        // 添加已有权限部门的子部门
        String sql = "";
        if(!setGroupIds.isEmpty()){
            Set<String> setParentGroupIds = new HashSet<>();
            setParentGroupIds.addAll(setGroupIds);
            for(String groupId: setParentGroupIds){
                sql = "select path_ from org_group where id_=? limit 1";
                List<Map<String,Object>>  list = DbUtil.getJdbcTemplate().queryForList(sql, groupId);
                if(list!=null && list.size()>0){
                    String path = MapUtil.getStr(list.get(0),"path_");
                    sql = "select id_ from org_group g where g.path_ like '"+path.replaceAll("_","\\_")+"\\_%'";
                    List<Map<String,Object>> list2 = DbUtil.getJdbcTemplate().queryForList(sql);
                    if(list2!=null && list2.size()>0){
                        for(Map<String,Object> row2: list2){
                            setGroupIds.add(MapUtil.getStr(row2, "id_"));
                        }
                    }
                }
            }
        }
        if(setGroupIds.isEmpty()){
            return new String[0];
        }
        return setGroupIds.toArray(new String[setGroupIds.size()]);
    }

    // 主管的含义，现在是todo manager!
    // 2022-05-18 通过人找到设计科室
    @Cacheable("currentMasterGroupIds")
    public String[] getCurrentMasterGroupIds(String userId) {
        Set<String> setGroupIds = new HashSet<>();
        //wss_dprt_manager
        //wss_dprt_assistant
        //wss_dprt_inter 增加内勤 2020/11/23

        List<ProjDesigndprt2> designdprt2 = projDesigndprt2Mapper.selectList(new QueryWrapper<ProjDesigndprt2>().lambda().gt(ProjDesigndprt2::getDesigndprtid, 0));
        for (ProjDesigndprt2 dprt : designdprt2){
            Set<String> uids = new HashSet<>();
//            if (StringUtils.isNotBlank(dprt.getDprtManager())){
//                String[] ss = dprt.getDprtManager().split(",");
//                uids.addAll(Arrays.asList(ss));
//            }
//            if (StringUtils.isNotBlank(dprt.getDprtAssistant())){
//                String[] ss = dprt.getDprtAssistant().split(",");
//                uids.addAll(Arrays.asList(ss));
//            }
            if (StringUtils.isNotBlank(dprt.getTodoManager())){
                String[] ss = dprt.getTodoManager().split(",");
                uids.addAll(Arrays.asList(ss));
            }
//            if (StringUtils.isNotBlank(dprt.getDprtInner())){
//                String[] ss = dprt.getDprtInner().split(",");
//                uids.addAll(Arrays.asList(ss));
//            }
            if (uids.contains(userId)){
                setGroupIds.add(dprt.getDprtid().toString());
            }

        }

//        if(listDprt!=null){
//            for(Map<String, Object> row: listDprt){
//                String dprtId = MapUtil.getStr(row, "dprtid");
//                setGroupIds.add(dprtId);
//            }
//        }
        // 添加已有权限部门的子部门
        String sql = "";
        if(!setGroupIds.isEmpty()){
            Set<String> setParentGroupIds = new HashSet<>();
            setParentGroupIds.addAll(setGroupIds);
            for(String groupId: setParentGroupIds){
                sql = "select path_ from org_group where id_=? limit 1";
                List<Map<String,Object>>  list = DbUtil.getJdbcTemplate().queryForList(sql, groupId);
                if(list!=null && list.size()>0){
                    String path = MapUtil.getStr(list.get(0),"path_");
                    sql = "select id_ from org_group g where g.path_ like '"+path.replaceAll("_","\\_")+"\\_%'";
                    List<Map<String,Object>> list2 = DbUtil.getJdbcTemplate().queryForList(sql);
                    if(list2!=null && list2.size()>0){
                        for(Map<String,Object> row2: list2){
                            setGroupIds.add(MapUtil.getStr(row2, "id_"));
                        }
                    }
                }
            }
        }
        if(setGroupIds.isEmpty()){
            return new String[0];
        }
        return setGroupIds.toArray(new String[setGroupIds.size()]);
    }



    // 作为出勤2张表的逻辑：TWSAP报表显示 + 内勤
    // 2022-05-18 通过人找到设计科室
    @Cacheable("currentAttendenceIds")
    public String[] getCurrentAttendenceIds(String userId) {
        Set<String> setGroupIds = new HashSet<>();
        List<ProjDesigndprt2> designdprt2 = projDesigndprt2Mapper.selectList(new QueryWrapper<ProjDesigndprt2>().lambda().gt(ProjDesigndprt2::getDesigndprtid, 0));
        for (ProjDesigndprt2 dprt : designdprt2){
            Set<String> uids = new HashSet<>();
            if (StringUtils.isNotBlank(dprt.getDprtInner())){
                String[] ss = dprt.getDprtInner().split(",");
                uids.addAll(Arrays.asList(ss));
            }
            if (StringUtils.isNotBlank(dprt.getTwsapStatManager())){
                String[] ss = dprt.getTwsapStatManager().split(",");
                uids.addAll(Arrays.asList(ss));
            }
            if (uids.contains(userId)){
                setGroupIds.add(dprt.getDprtid().toString());
            }

        }


        // 添加已有权限部门的子部门
        String sql = "";
        if(!setGroupIds.isEmpty()){
            Set<String> setParentGroupIds = new HashSet<>();
            setParentGroupIds.addAll(setGroupIds);
            for(String groupId: setParentGroupIds){
                sql = "select path_ from org_group where id_=? limit 1";
                List<Map<String,Object>>  list = DbUtil.getJdbcTemplate().queryForList(sql, groupId);
                if(list!=null && list.size()>0){
                    String path = MapUtil.getStr(list.get(0),"path_");
                    sql = "select id_ from org_group g where g.path_ like '"+path.replaceAll("_","\\_")+"\\_%'";
                    List<Map<String,Object>> list2 = DbUtil.getJdbcTemplate().queryForList(sql);
                    if(list2!=null && list2.size()>0){
                        for(Map<String,Object> row2: list2){
                            setGroupIds.add(MapUtil.getStr(row2, "id_"));
                        }
                    }
                }
            }
        }
        if(setGroupIds.isEmpty()){
            return new String[0];
        }
        return setGroupIds.toArray(new String[setGroupIds.size()]);
    }

    // 作为统计报表的逻辑：TWSAP报表显示
    // 2022-05-18 通过人找到设计科室
    @Cacheable("currentStatIds")
    public String[] getCurrentStatIds(String userId) {
        Set<String> setGroupIds = new HashSet<>();

        List<ProjDesigndprt2> designdprt2 = projDesigndprt2Mapper.selectList(new QueryWrapper<ProjDesigndprt2>().lambda().gt(ProjDesigndprt2::getDesigndprtid, 0));
        for (ProjDesigndprt2 dprt : designdprt2){
            Set<String> uids = new HashSet<>();

            if (StringUtils.isNotBlank(dprt.getTwsapStatManager())){
                String[] ss = dprt.getTwsapStatManager().split(",");
                uids.addAll(Arrays.asList(ss));
            }
            if (uids.contains(userId)){
                setGroupIds.add(dprt.getDprtid().toString());
            }

        }


        // 添加已有权限部门的子部门
        String sql = "";
        if(!setGroupIds.isEmpty()){
            Set<String> setParentGroupIds = new HashSet<>();
            setParentGroupIds.addAll(setGroupIds);
            for(String groupId: setParentGroupIds){
                sql = "select path_ from org_group where id_=? limit 1";
                List<Map<String,Object>>  list = DbUtil.getJdbcTemplate().queryForList(sql, groupId);
                if(list!=null && list.size()>0){
                    String path = MapUtil.getStr(list.get(0),"path_");
                    sql = "select id_ from org_group g where g.path_ like '"+path.replaceAll("_","\\_")+"\\_%'";
                    List<Map<String,Object>> list2 = DbUtil.getJdbcTemplate().queryForList(sql);
                    if(list2!=null && list2.size()>0){
                        for(Map<String,Object> row2: list2){
                            setGroupIds.add(MapUtil.getStr(row2, "id_"));
                        }
                    }
                }
            }
        }
        if(setGroupIds.isEmpty()){
            return new String[0];
        }
        return setGroupIds.toArray(new String[setGroupIds.size()]);
    }


    // 作为主管/助理的部门以及子部门 id(不含内勤)
    // 2022-05-18 通过人找到设计科室
    @Cacheable("currentMasterGroupIds2")
    public String[] getCurrentMasterGroupIds2(String userId) {
        Set<String> setGroupIds = new HashSet<>();
        //wss_dprt_manager
        //wss_dprt_assistant
        //wss_dprt_inter 增加内勤 2020/11/23
//        String sql = "select dprtid from wss_dprt_manager where uid=? and active=1\n" +
//                " union " +
//                " select dprtid from wss_dprt_assistant where uid=? and active=1";
//        List<Map<String,Object>>  listDprt = DbUtil.getJdbcTemplate().queryForList(sql, userId, userId);
//        if(listDprt!=null){
//            for(Map<String, Object> row: listDprt){
//                String dprtId = MapUtil.getStr(row, "dprtid");
//                setGroupIds.add(dprtId);
//            }
//        }
        List<ProjDesigndprt2> designdprt2 = projDesigndprt2Mapper.selectList(new QueryWrapper<ProjDesigndprt2>().lambda().gt(ProjDesigndprt2::getDesigndprtid, 0));
        for (ProjDesigndprt2 dprt : designdprt2){
            Set<String> uids = new HashSet<>();
//            if (StringUtils.isNotBlank(dprt.getDprtManager())){
//                String[] ss = dprt.getDprtManager().split(",");
//                uids.addAll(Arrays.asList(ss));
//            }
//            if (StringUtils.isNotBlank(dprt.getDprtAssistant())){
//                String[] ss = dprt.getDprtAssistant().split(",");
//                uids.addAll(Arrays.asList(ss));
//            }
            if (StringUtils.isNotBlank(dprt.getTodoManager())){
                String[] ss = dprt.getTodoManager().split(",");
                uids.addAll(Arrays.asList(ss));
            }
            if (uids.contains(userId)){
                setGroupIds.add(dprt.getDprtid().toString());
            }

        }


        // 添加已有权限部门的子部门
        String sql = "";
        if(!setGroupIds.isEmpty()){
            Set<String> setParentGroupIds = new HashSet<>();
            setParentGroupIds.addAll(setGroupIds);
            for(String groupId: setParentGroupIds){
                sql = "select path_ from org_group where id_=? limit 1";
                List<Map<String,Object>>  list = DbUtil.getJdbcTemplate().queryForList(sql, groupId);
                if(list!=null && list.size()>0){
                    String path = MapUtil.getStr(list.get(0),"path_");
                    sql = "select id_ from org_group g where g.path_ like '"+path.replaceAll("_","\\_")+"\\_%'";
                    List<Map<String,Object>> list2 = DbUtil.getJdbcTemplate().queryForList(sql);
                    if(list2!=null && list2.size()>0){
                        for(Map<String,Object> row2: list2){
                            setGroupIds.add(MapUtil.getStr(row2, "id_"));
                        }
                    }
                }
            }
        }
        if(setGroupIds.isEmpty()){
            return new String[0];
        }
        return setGroupIds.toArray(new String[setGroupIds.size()]);
    }


    /**
     * 根据用户id获取当前部门（不包含子部门）
     *
     * @param userId
     * @return
     */
    public Set<String> getUserGroupIdsByUserId(String userId) {
        String sql = "select t1.id_ from org_group t1 left join org_relation t2 on t1.id_ = t2.group_id_ " +
                "where t2.type_ = 'groupUser' and t2.status_=1 and t2.user_id_ = '{}'";
        List<Map<String,Object>> ids = jdbcTemplate.queryForList(StrUtil.format(sql,userId));
        Set<String> groupIds = new HashSet();
        for (Map<String,Object> map:ids){
            groupIds.add(map.get("id_").toString());
        }
        return groupIds;
    }

    /**
     * 根据用户id获取用户所在部门班组 多个
     *
     * @param userId
     * @return
     */
    public List<String> getDprtIdsByUserId(Long userId) {
        List<String> dprtIds = new ArrayList<>();
        String sql = "select g.id_ groupId, g.name_ groupName from org_user u,org_relation r,org_group g " +
                " where u.id_=r.user_id_ and r.type_='groupUser' and g.id_=r.group_id_ and r.status_=1 and u.id_=? ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, userId);
        if(list!=null && list.size()>0){
            for(Map<String, Object> map:list){
                dprtIds.add(map.get("groupId").toString());
            }
        }
        return dprtIds;
    }

    public String getFullGroupNameByUserId(Long userId){
        List<String> groupids = getDprtIdsByUserId(userId);
        if (groupids != null && groupids.size() > 0){
            String aa = groupids.get(0);
            return getFullGroupName(aa);
        }
        return "";
    }

    public String getFullGroupNameByUserId(String userId){
        List<String> groupids = getDprtIdsByUserId(Long.parseLong(userId));
        if (groupids != null && groupids.size() > 0){
            String aa = groupids.get(0);
            return getFullGroupName(aa);
        }
        return "";
    }

    /**
     * 根据部门班组ID获取名称
     * @param groupId
     * @return
     */
    public String getGroupNameById(String groupId){
        Group g = groupManager.get(groupId);
        return g!=null? g.getGroupName(): "";
    }

    public String getGroupNameByIds(List<String> groupIds){
        if (groupIds != null){
            return groupIds.stream().map(this::getGroupNameById).collect(Collectors.joining(","));
        }else{
            return "";
        }
    }

    /**
     * 根据用户获取部门
     *
     * @param uid
     * @return
     */
    public Long dprtidByUid(Long uid) {
        String sql = "SELECT dprtid FROM org_users WHERE id_='" + uid + "' limit 1";
        try {
            return jdbcTemplate.queryForObject(sql, Long.class);
        } catch (Exception e) {
            return 0L;
        }
    }

    /**
     * 修复组织调整后列表顺序不对的数据
     * todo 后面如果添加调整部门顺序方法后，需要去把数据刷对，或者直接调用本方法刷新
     */
    public void repair() {
        String sql = "update org_group t ,(SELECT id_,parent_id_,name_, @Pn:=parent_id_, path_,\n" +
                "@path:=(\n" +
                "SELECT GROUP_CONCAT(\n" +
                "SUBSTRING_INDEX( \n" +
                "@Pn:= (SELECT CONCAT(parent_id_,'|',id_) FROM org_group WHERE id_=SUBSTRING_INDEX(@Pn,'|',1)),\n" +
                "'|',\n" +
                "-1 ) \n" +
                "ORDER BY id_ DESC SEPARATOR '_' )\n" +
                "FROM org_group WHERE @Pn IS NOT NULL ORDER BY id_ ASC ) \n" +
                "AS path,\n" +
                "LENGTH (@path) - LENGTH (REPLACE(@path, '_', ''))+1 AS lv\n" +
                "FROM org_group) t1 \n" +
                "set t.path_ = IF(length(t1.path)>0,concat(t1.path,'_',t.id_),t.id_),\n" +
                "t.`level` = IF(t1.lv>0,t1.lv,0)\n" +
                "where t.id_ = t1.id_";
        String sql1 = "update org_group t\n" +
                "set t.isLeaf = 1\n" +
                "where t.id_ not in (select o.parent_id_ from (select parent_id_ from org_group) o)";
        String sql2 = "update org_group t\n" +
                "set t.isLeaf = 0\n" +
                "where t.id_ in (select o.parent_id_ from (select parent_id_ from org_group) o)";
        // 刷新org_group path_ 路径和层级 level
        jdbcTemplate.execute(sql);
        // 刷新org_group 底层的(没有下级)isLeaf = 1
        jdbcTemplate.execute(sql1);
        // 刷新org_group 不是底层的(有下级)isLeaf = 0
        jdbcTemplate.execute(sql2);
    }

    // 获取部门全称
    public String getFullGroupName(String groupId){
        if (StringUtils.isBlank(groupId)){
            return "";
        }
        List<String> names = new ArrayList<>();
        Group g = groupManager.get(groupId);
        names.add(g.getName());
        while (g.getParentId() != null){
            g = groupManager.get(g.getParentId());
            if (g != null) {
                names.add(0, g.getName());
            } else {
                break;
            }

        }
        return String.join(" / ", names);
    }


    public String getGroupFullName(String groupId) {
        String sql = "SELECT fullname FROM `org_group_fullname` WHERE group_id = '{}'";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(StrUtil.format(sql, groupId));
        if (mapList.size() > 0) {
            return mapList.get(0).get("fullname").toString();
        }

        return "";
    }


    // 获取部门的角色
    public List<OrgRelation> getOrgRelationByGroup(String groupId) {
        if (StringUtils.isBlank(groupId)) {
            return EMPTY_LIST;
        }


        return orgRelationDao.getRelationsByParam(Lists.list("roleGroup"), null, groupId, null);
        // return etechRelationService.getGroupPost(groupId);
    }



    @Transactional(rollbackFor = Exception.class)
    public void refreshGroupView(){
        jdbcTemplate.update("delete from org_group_view;");
        List<EtechOrgTree> groupTree = getGroupTree();
        List<GroupView> result = new ArrayList<>();
        for (EtechOrgTree tree: groupTree){
            getGroupViewByTree(tree, 0, new GroupView(), result);
        }
        for (GroupView groupView: result){
            groupViewMapper.insert(groupView);
        }
    }

    public List<EtechOrgTree> getGroupTree() {
        List<EtechOrgTree> groupTreeList = new ArrayList();
        List<Group> groupList = this.groupManager.getAll();
        for (Group group : groupList) {
            EtechOrgTree groupTree = new EtechOrgTree(group);
            groupTreeList.add(groupTree);
        }
        return EtechOrgTree.list2tree(groupTreeList);
    }

    private void getGroupViewByTree(EtechOrgTree orgTree, int level, GroupView view,  List<GroupView> result){
        if (orgTree == null){
            return;
        }
        view.setCode(orgTree.getCode());
        view.setName(orgTree.getName());
        view.setGroupId(orgTree.getId());
        if (orgTree.getType() != null){
            if (orgTree.getType().equals(0)){
                view.setLevelId2(Long.parseLong(orgTree.getId()));
                view.setLevelName2(orgTree.getName());
            }else if (orgTree.getType().equals(1)){
                view.setLevelId3(Long.parseLong(orgTree.getId()));
                view.setLevelName3(orgTree.getName());
            }else if (orgTree.getType().equals(2)){
                view.setLevelId4(Long.parseLong(orgTree.getId()));
                view.setLevelName4(orgTree.getName());
            }else if (orgTree.getType().equals(3)){
                view.setLevelId5(Long.parseLong(orgTree.getId()));
                view.setLevelName5(orgTree.getName());
            }else if (orgTree.getType().equals(4)){
                view.setLevelId6(Long.parseLong(orgTree.getId()));
                view.setLevelName6(orgTree.getName());
            }
        }
        result.add(view);
        if (orgTree.getChildren() != null){
            for (EtechOrgTree subTree : orgTree.getChildren()){
                GroupView copyView = new GroupView();
                BeanUtil.copyProperties(view, copyView);
                getGroupViewByTree(subTree,level+1,copyView, result);
            }
        }
    }


}
